import React, { Component, createRef } from "react";
import { Form, Input, Button, message } from "antd";
import {
  MobileOutlined,
  FieldNumberOutlined,
  KeyOutlined,
} from "@ant-design/icons";
import Captcha from "../../components/Captcha";
// 导入请求资源
import url from "../../config/url";
import req from "../../http/req";
import { withRouter } from "react-router-dom";

class Mobilelogin extends Component {
  constructor(props) {
    super(props);
    this.capRef = createRef();
    this.formRef = createRef();
  }
  t = null
  state = {
    time: 60, // 倒计时的时长
    sentCode: false, // 标志是否已经完成短信的获取【算是性能优化，如果没有获取过短信 ，那么肯定不能让其发送ajax请求后端验证】
    enabled: true, // 指定按钮是否可以被点击
  };
  render() {
    return (
      <Form
        ref={this.formRef}
        name="normal_login"
        className="login-form"
        initialValues={{}}
        onFinish={this.onFinish}
      >
        <Form.Item
          name="mobile"
          rules={[
            {
              required: true,
              message: "请输入手机号！",
            },
          ]}
        >
          <Input
            prefix={<MobileOutlined className="site-form-item-icon" />}
            placeholder="手机号"
            maxLength="11"
          />
        </Form.Item>
        <Form.Item
          name="captcha"
          rules={[
            {
              required: true,
              message: "请输入图形验证码！",
            },
          ]}
        >
          <div>
            <Input
              prefix={<KeyOutlined className="site-form-item-icon" />}
              type="text"
              placeholder="图形验证码"
              style={{ width: "70%", marginRight: "7px" }}
            />
            <Captcha h={32} w={96} setKey={this.getKey} ref={this.capRef} />
          </div>
        </Form.Item>
        <Form.Item
          name="code"
          rules={[
            {
              required: true,
              message: "请输入短信验证码！",
            },
          ]}
        >
          <div>
            <Input
              prefix={<FieldNumberOutlined className="site-form-item-icon" />}
              type="text"
              maxLength="6"
              style={{ width: "60%", marginRight: "7px" }}
              placeholder="短信验证码"
            />
            <Button
              type="primary"
              onClick={this.sendCode}
              disabled={!this.state.enabled}
              style={{ width: "38%" }}
            >
              {this.state.enabled
                ? "获取短信"
                : `重新获取（${this.state.time}）`}
            </Button>
          </div>
        </Form.Item>
        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            className="login-form-button"
            block
            style={{ borderRadius: "15px" }}
            disabled={!this.state.sentCode}
          >
            登录
          </Button>
        </Form.Item>
      </Form>
    );
  }
  // 提交处理程序
  onFinish = (values) => {
    // console.log(values);
    let { code, mobile } = values
    let params = { mobile, code, requestId: this.state.requestId }
    req.post(url.MobileLogin, params).then(res => {
      if(res.data.errNo === 0) {
        message.success("登录成功！", 2, () => {
          this.props.history.push("/dashboard")
        })
      }else {
        message.error(res.data.errText, 2, () => {
          this.capRef.current.loadCaptcha()
        })
      }
    })
  };

  // 获取验证码key值的方法
  getKey = (key) => {
    this.setState({
      key,
    });
  };
  sendCode = () => {
    let { mobile, captcha } = this.formRef.current.getFieldsValue()
    // console.log(mobile,captcha);
    if(/^1[3-9]\d{9}$/.test(mobile) && captcha) {
      req.post(url.VerifyCaptcha, { captcha, key: this.state.key }).then(res => {
        if(res.data.errNo === 0) {
          let token = res.data.context.token
          req.post(url.SendCode, {mobile, token, type:0}).then(res => {
            // console.log(res);
            if(res.data.errNo === 0) {
              this.setState({
                requestId: res.data.requestId,
                sentCode: true
              })
              message.success("发送短信成功", 2)
              this.timedown()
            }else {
              message.error(res.data.errText, 2, () => {
                this.capRef.current.loadCaptcha()
              })
            }
          })
        }else {
          // 短信发送失败
          message.error(res.data.errText, 2, () => {
            this.capRef.current.loadCaptcha()
          })
        }
      })
    }else {
      // 验证码验证失败
      message.error("请输入正确的手机号和图形验证码")
    }
    this.timedown();
  };
  timedown = () => {
    if (this.state.time === 0) {
      this.setState({
        time: 60,
        enabled: true,
      });
    } else {
      this.setState({
        time: this.state.time - 1,
        enabled: false,
      });
      this.t = setTimeout(() => {
        this.timedown();
      }, 1000);
    }
  };
  componentWillUnmount(){
    clearTimeout(this.t)
  }
}

export default withRouter(Mobilelogin);
